    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.MumuUser;
import service.MumuUserFacadeREST;
import utilities.ReadSmtp;

/**
 *
 * @author andrew
 */
@WebServlet(name = "GrantAccessServlet", urlPatterns = {"/GrantAccessServlet"})
//@ServletSecurity(@HttpConstraint(rolesAllowed={"admin"})) // solo admin può dare l'autorizzazione
public class GrantAccessServlet extends HttpServlet {

    @EJB
    private MumuUserFacadeREST userManager;
    private Session session;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("1");
        
        final ReadSmtp readSmtp = new ReadSmtp(request);

        HttpSession httpSession = request.getSession();
        if (httpSession.getAttribute("logged") == null || !httpSession.getAttribute("logged").equals("logged")) {
            response.sendRedirect("home.jsp");
        } else {

            // trovo utente desiderato
            String nameSurname = (String) httpSession.getAttribute("validatingName");
            String email = (String) httpSession.getAttribute("validatingEmail");
            //String password = request.getParameter("password");
            //String qualification = request.getParameter("qualification");
            String role = (String) httpSession.getAttribute("role");
            
            
            
            System.out.println("2");

            System.out.println("Name Surname: " + nameSurname);
            System.out.println("Mail: " + email);
            System.out.println("Role: " + role);

            int idUser = -1;

            List<MumuUser> listUser = userManager.findAll();
            Iterator<MumuUser> itUser = listUser.iterator();
            while (itUser.hasNext()) {
                MumuUser u = itUser.next();
                System.out.println("NameSurname_ciclo: " + u.getNameSurname());
                System.out.println("Mail_ciclo: " + u.getMail());
                if ((u.getNameSurname().equals(nameSurname))
                        && (u.getMail().equals(email))) {
                    idUser = u.getIdUser();
                    System.out.println("id_ciclo: " + idUser);
                    //System.out.println("ID dell'utente trovato: "+u.getIdUser());
                }
            }
            System.out.println("3");
            String stringForMail = "";

            if (idUser != -1) {
                MumuUser waitingUser = userManager.find(idUser);
                System.out.println("4");
                if (role.equals("admin")) {
                    waitingUser.setIsAdministrator(true);
                    waitingUser.setIsValidated(true);
                    userManager.edit(waitingUser);
                    stringForMail = "Amministratore di UniverseCreator.";
                    System.out.println("5");

                } else if (role.equals("guest")) {
                    waitingUser.setIsAdministrator(false);
                    waitingUser.setIsValidated(true);
                    userManager.edit(waitingUser);
                    stringForMail = "Creatore di universi in UniverseCreator.";
                    System.out.println("6");

                } else if (role.equals("ignore")) {
                    userManager.remove(waitingUser);
                    stringForMail = "rifiutato.";
                    System.out.println("7");

                }
            }

            // invio notifica per mail della decisione presa dall'amministratore
            // invio notifica richiesta tramite mail
            System.out.println("8");
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( email, "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
                message.setSubject("UniverseCreator: esito registrazione");
                String content ="";
                if(stringForMail.equals("Amministratore di UniverseCreator.") || 
                        stringForMail.equals("Creatore di universi in UniverseCreator.")){
                    
                    content = "Gentile " + nameSurname + ",<br/><br/>"
                        + "Il tuo account &egrave; stato registrato con successo con privilegi di "+stringForMail+"<br/>"
                        + "<br/>"
                        + "Per accedere all'area riservata utilizza<br/> "
                        + "username: " + email + "<br/>"
                        + "e password da te inserita al momento della registrazione.<br/>"
                        + "<br/><br/>Ti ricordiamo che se non ricordi pi&ugrave; la password, puoi recuperarla in qualsiasi momento semplicemente cliccando sul link che trovi in homepage."
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                    
                }else if(stringForMail.equals("rifiutato.")){
                    
                    content = "Gentile " + nameSurname + ",<br/><br/>"
                        + "Il tuo account "+ email +" &egrave; stato rifiutato.<br/>"
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                    
                }
                
                
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            System.out.println("9");
            //service.addUser(username, email, password, qualification, role);
            response.sendRedirect("admin.jsp?name="+nameSurname+"&mail="+email+"&s="+role);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

//        // check if session is expired
//        HttpSession session = request.getSession(false);// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {         
//            processRequest(request, response);
//        } else {
//            response.sendRedirect("/home.jsp");
//        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

//        // check if session is expired
//        HttpSession session = request.getSession(false);// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {         
//            processRequest(request, response);
//        } else {
//            response.sendRedirect("/home.jsp");
//        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
